<?php


namespace app\home\model\page\shop;


use app\api\model\dao\FlashSale;
use app\library\Error;
use app\library\PageBase;

class AddFlashSale extends PageBase
{
    private $objFlashSaleModel;

    public function __construct()
    {
        parent::__construct();
        $this->objFlashSaleModel = new FlashSale();
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        if ($param['start_time'] > $param['end_time']) {
            return $this->getRes(Error::ERR_PARAM, '结束时间必须大于开始时间');
        }

        if ($param['buy_limit'] > $param['goods_num']) {
            return $this->getRes(Error::ERR_PARAM, '限购数量必须小于等于商品总数');
        }
        $ret = $this->objFlashSaleModel->addFlashSale($param);
        if ($ret === false) {
            return $this->getRes(Error::ERR_SYS);
        }

        return $this->getRes();
    }


    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'title' => 'require',
            'description' => 'require',
            'goods_id' => 'require|number',
            'goods_name' => 'require',
            'price' => 'require|float',
            'goods_num' => 'require|between:1,10000',
            'buy_limit' => 'require|number',
            'start_time' => 'require',
            'end_time' => 'require',
        ];
        $msg = [
            'title.require' => '名称必填',
            'description.require' => '描述必填',
            'goods_id.require' => '商品ID必填',
            'goods_name.require' => '商品名称必填',
            'price.require' => '价格必填',
            'goods_num.require' => '数量必填',
            'buy_limit.require' => '购买限制必填',
            'start_time.require' => '开始时间必填',
            'end_time.require' => '结束时间必填',
        ];

        $validate = new \think\Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }
}